require_relative 'util/tauri'

File.readlines('.env', chomp: true).each do |line|
  ENV[$1] = $2 if line =~ /\A([^=]+)=(.*)\z/
end if File.exist?('.env')

default_platform(:android)

def use_prebuilt_openssl
  openssl_path = File.join(Dir.getwd, 'downloads', 'android_openssl-master', 'ssl_1.1')
  unless File.directory?(openssl_path)
    zip_path = File.join(Dir.getwd, 'downloads', 'android_openssl-master.tar.gz')
    download_file(url: 'https://github.com/KDAB/android_openssl/archive/refs/heads/master.tar.gz',
                  destination_path: zip_path)
    sh("tar", "-xzf", zip_path, "-C", "downloads")
  end
  ENV['OPENSSL_NO_VENDOR'] = '1'
  ENV['OPENSSL_INCLUDE_DIR'] = File.join(openssl_path, 'include')
  ENV['AARCH64_LINUX_ANDROID_OPENSSL_LIB_DIR'] = File.join(openssl_path, 'arm64-v8a')
  ENV['ARMV7_LINUX_ANDROIDEABI_OPENSSL_LIB_DIR'] = File.join(openssl_path, 'armeabi-v7a')
  ENV['I686_LINUX_ANDROID_OPENSSL_LIB_DIR'] = File.join(openssl_path, 'x86')
  ENV['X86_64_LINUX_ANDROID_OPENSSL_LIB_DIR'] = File.join(openssl_path, 'x86_64')
end

def set_signing_properties
  ENV["GRADLE_OPTS"] = {
    "android.injected.signing.store.file" => ENV["ANDROID_SIGNING_STORE_FILE"],
    "android.injected.signing.store.password" => ENV["ANDROID_SIGNING_STORE_PASSWORD"],
    "android.injected.signing.key.alias" => ENV["ANDROID_SIGNING_KEY_ALIAS"],
    "android.injected.signing.key.password" => ENV["ANDROID_SIGNING_KEY_PASSWORD"],
  }.map { |k, v| "-Dorg.gradle.project.#{k}=#{v}" }.join(" ")
end

platform :android do

  desc "Build apk or aab"
  lane :build do |options|
    use_prebuilt_openssl if ENV["OPENSSL_USE_PREBUILT"] == "1"
    set_signing_properties if ENV["ANDROID_SIGNING_STORE_FILE"]

    puts "options: #{options}"

    Tauri::Android.build(aab: options[:aab] != false, apk: options[:apk], targets: options[:targets]&.split(',') || [],
                         features: ENV["OPENSSL_USE_PREBUILT"] == "1" ? [] : ["vendored-openssl"])
  end

  desc "Deploy a new version to the Google Play"
  lane :deploy do
    build(aab: true, apk: false)

    upload_to_play_store(
      track: "internal",
      skip_upload_metadata: true,
      skip_upload_changelogs: true,
      skip_upload_images: true,
      skip_upload_screenshots: true,
    )
  end

  desc "Download the signed universal APK from the Google Play"
  lane :download_apk do
    version = Gem::Version::create(JSON.load_file('../package.json')['version'])
    version_code = version.segments[0] * 1000000 + version.segments[1] * 1000 + version.segments[2]

    download_universal_apk_from_google_play(
      version_code: version_code,
      destination: File.join(Dir.getwd, "downloads", "webOS.Dev.Manager_#{version}_universal.apk"))
  end
end
